package riconosci.Colori;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import android.graphics.Color;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.Size;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.widget.Toast;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.Surface;

public class CameraColorActivity extends Activity {
	private CameraSurfaceView mPreview;
	//PImage gBuffer;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
     // Hide the window title.
        requestWindowFeature(Window.FEATURE_NO_TITLE);		
        // Create our Preview view and set it as the content of our activity.
        mPreview = new CameraSurfaceView(this);
        setContentView(mPreview);
    }
}

// ----------------------------------------------------------------------

class CameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback, Camera.PreviewCallback {
	  // Object that accesses the camera, and updates our image data
	  // Using ideas pulled from 'Android Wireless Application Development', page 340

	  SurfaceHolder mHolder;
	  Camera mCamera = null;
	  Camera.Size prevSize;

	  // SurfaceView Constructor:  : ---------------------------------------------------
	  CameraSurfaceView(Context context) {
	    super(context);
	    // Processing PApplets come with their own SurfaceView object which can be accessed
	    // directly via its object name, 'surfaceView', or via the below function:
	    // mHolder = surfaceView.getHolder();
        mHolder = getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	  }

	  // SurfaceHolder.Callback stuff: ------------------------------------------------------
	  public void surfaceCreated (SurfaceHolder holder) {
		// When the SurfaceHolder is created, create our camera, and register our
		    // camera's preview callback, which will fire on each frame of preview:
		  mCamera = Camera.open();
		  mCamera.setPreviewCallback(this);
		  
		    Camera.Parameters parameters = mCamera.getParameters();
		    // Find our preview size, and init our global PImage:
		    prevSize = parameters.getPreviewSize();
		   
		  
	        try {
	           mCamera.setPreviewDisplay(holder);
	        } catch (IOException exception) {
	            mCamera.release();
	            mCamera = null;
	            // TODO: add more exception handling logic here
	        }
	  }  

	  public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
	    // Start our camera previewing:
	    mCamera.startPreview();
	  }

	  public void surfaceDestroyed (SurfaceHolder holder) {
	    // Give the cam back to the phone:
	    mCamera.stopPreview();
	    mCamera.release();
	    mCamera = null;
	  }

	  //  Camera.PreviewCallback stuff: ------------------------------------------------------
	  public void onPreviewFrame(byte[] data, Camera cam) {
		  ByteArrayOutputStream outstr = new ByteArrayOutputStream();
          Rect rect = new Rect(0, 0, prevSize.width, prevSize.height); 
          YuvImage yuvimage=new YuvImage(data,ImageFormat.NV21,prevSize.width,prevSize.height,null);
          yuvimage.compressToJpeg(rect, 100, outstr);
          Bitmap bmp = BitmapFactory.decodeByteArray(outstr.toByteArray(), 0, outstr.size());
		  
          int[] pixels = new int[bmp.getHeight()*bmp.getWidth()];
          bmp.getPixels(pixels, 0, bmp.getWidth(), 0, 0, bmp.getWidth(), bmp.getHeight());
          for (int i=0; i<bmp.getWidth()*5; i++)
              pixels[i] = Color.BLUE;
          bmp.setPixels(pixels, 0, bmp.getWidth(), 0, 0, bmp.getWidth(), bmp.getHeight());
          
          data=handleBitmap(bmp);
          
          
		// This is called every frame of the preview.  Update our global PImage.
		//Now instead of this i nead something i can work on with pixels (this continuisly save picture)
		  /*FileOutputStream outStream = null;
			try {
				
				YuvImage yuvimage = new YuvImage(data,ImageFormat.NV21,prevSize.width, prevSize.height,null);
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				yuvimage.compressToJpeg(new Rect(0,0,prevSize.width, prevSize.height), 80, baos);
				
				outStream = new FileOutputStream(String.format("/sdcard/%d.jpg", System.currentTimeMillis()));	
				outStream.write(baos.toByteArray());
				outStream.close();
				
				Log.d("COMPLETATO", "onPreviewFrame - wrote bytes: " + data.length);
			} catch (FileNotFoundException e) {
				Log.d("COMPLETATO", "onPreviewFrame - wrote bytes: " + e.getMessage());
				
			} catch (IOException e) {
				Log.d("COMPLETATO", "onPreviewFrame - wrote bytes: " + e.getMessage());
			} finally {
			}*/
			CameraSurfaceView.this.invalidate();
	  }
	  
	  public byte[] handleBitmap(Bitmap image) {
			int w = image.getWidth(), h = image.getHeight();
			int[] rgb = new int[w * h];
			byte[] yuv = new byte[w * h];

			image.getPixels(rgb, 0, w, 0, 0, w, h);
			populateYUVLuminanceFromRGB(rgb, yuv, w, h);
			
			return yuv;
		}

		// Inspired in large part by:
		// http://ketai.googlecode.com/svn/trunk/ketai/src/edu/uic/ketai/inputService/KetaiCamera.java
		private void populateYUVLuminanceFromRGB(int[] rgb, byte[] yuv420sp, int width, int height) {
			for (int i = 0; i < width * height; i++) {
				float red = (rgb[i] >> 16) & 0xff;
				float green = (rgb[i] >> 8) & 0xff;
				float blue = (rgb[i]) & 0xff;
				int luminance = (int) ((0.257f * red) + (0.504f * green) + (0.098f * blue) + 16);
				yuv420sp[i] = (byte) (0xff & luminance);
			}
		}

	  
	  
	}
